import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { Form, message } from "antd";
import moment from "moment";

import { IForm } from "@/components";
import { regExpMap, roleTypeMap } from "@/utils/consts";

import type { RecordItem } from "../type";
import type { FormItemConfig } from "@/components/FormItem";
import request from "@/utils/request";

interface Props {
	selRecord?: RecordItem;
	// termIdSelectOptions?: [];
	// classifySelectOptions?: [];
}

const InfoForm = forwardRef((props: Props, ref) => {
	const [form] = Form.useForm();
	const [termIdSelectOptions, setTermIdSelectOptions] = useState();
	const [classifySelectOptions, setClassifySelectOptions] = useState();

	//
	const queryTermOptions = () => {
		// 管理员详情接口
		request("courseManageQueryTermOptions", { data: {} }).then(res => {
			if (res.code === 0 && res.data) {
				setTermIdSelectOptions(res.data);
			}
		});
	};

	const queryClassifyOptions = () => {
		// 管理员详情接口
		request("courseManageQueryClassifyOptions", { data: {} }).then(res => {
			if (res.code === 0 && res.data) {
				setClassifySelectOptions(res.data);
			}
		});
	};

	useEffect(() => {
		queryTermOptions();
		queryClassifyOptions();

		if (props.selRecord) {
			queryById();
		}
	}, [props.selRecord]);

	useImperativeHandle(ref, () => ({
		validateFields: () => {
			return form
				.validateFields()
				.then(value => {
					return {
						...value
						// accountExpire: formatDateShowTime(value.accountExpire),
					};
				})
				.catch((error: any) => {
					message.warn("请完善课程信息");
					throw error;
				});
		}
	}));

	const queryById = () => {
		// 管理员详情接口
		request("courseManageQueryById", { data: { courseId: props.selRecord?.id } }).then(res => {
			if (res.code === 0 && res.data) {
				const { accountExpire } = res.data;
				form.setFieldsValue({
					...res.data
					// accountExpire: momentDate(accountExpire)
				});
			}
		});
	};

	const formItemsConfig: FormItemConfig[] = [
		{
			type: "input",
			formItemProps: {
				label: "课程编号",
				name: "courseNo",
				rules: [{ required: true }]
			}
		},
		{
			type: "input",
			formItemProps: {
				label: "课程名称",
				name: "courseName",
				rules: [{ required: true }]
			}
		},
		{
			type: "select",
			formItemProps: {
				label: "课程学期",
				name: "termId",
				rules: [{ required: true }]
			},
			childProps: {
				// mode:"multiple",
				options: termIdSelectOptions
			}
		},
		{
			type: "select",
			formItemProps: {
				label: "课程类型",
				name: "classifyId",
				rules: [{ required: true }]
			},
			childProps: {
				// mode:"multiple",
				options: classifySelectOptions
			}
		},
		{
			type: "input",
			formItemProps: {
				label: "学分",
				name: "credit",
				rules: [{ required: true }]
			}
		}
	];

	return (<div><IForm layout="vertical" form={form} formItemsConfig={formItemsConfig}></IForm></div>);
});

InfoForm.displayName = "InfoForm";

export default InfoForm;
